package com.yqg.education.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yqg.education.common.Result;
import com.yqg.education.entity.*;
import com.yqg.education.mapper.*;
import com.yqg.education.service.IExamLogService;
import com.yqg.education.service.IExampaperService;
import com.yqg.education.service.IExamquestionService;
import com.yqg.education.service.IQuestionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * ExampaperServiceImpl 服务实现类
 *
 * @author zxf
 * @since 2025-04-16
 */
@Service
public class ExampaperServiceImpl extends ServiceImpl<ExampaperMapper, Exampaper> implements IExampaperService {
    @Resource
    private ExampaperMapper exampaperMapper;
    @Resource
    private ExamSignMapper examSignMapper;
    @Resource
    private ExamquestionMapper examquestionMapper;

    @Resource
    private IQuestionService questionService;
    @Resource
    private IExamquestionService examquestionService;
    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private IExamLogService examLogService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> stuFindExampaperPage(Long userId, Long courseId) {
        List<Question> questionList = new ArrayList<>();

        // 根据学员ID和课程ID查询试卷ID
        Long exampaperId = examSignMapper.getExampaperIdByStuIdAndCourseId(userId, courseId);

        if (exampaperId == null) {
            // 不存在已分配试卷，随机选择一份试卷
            List<Long> exampaperIdList = exampaperMapper.getIdByCourseId(courseId);
            List<Long> newExampaperIdList = new ArrayList<>();
            newExampaperIdList.addAll(exampaperIdList);
            if (!exampaperIdList.isEmpty()) {
                // 查找已使用的试卷
                LambdaQueryWrapper<ExamLog> examLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
                examLogLambdaQueryWrapper.eq(ExamLog::getCourseId, courseId);
                examLogLambdaQueryWrapper.eq(ExamLog::getIsDelete, 0);
                Set<Long> exampaperIds = examLogService.list(examLogLambdaQueryWrapper).stream().map(ExamLog::getExampaperId).collect(Collectors.toSet());
                if (exampaperIds.size() > 0) {
                    newExampaperIdList.removeAll(exampaperIds);
                }
                if (newExampaperIdList.size() > 0) {
                    int randomIndex = ThreadLocalRandom.current().nextInt(newExampaperIdList.size());
                    exampaperId = newExampaperIdList.get(randomIndex);
                } else {
                    int randomIndex = ThreadLocalRandom.current().nextInt(exampaperIdList.size());
                    exampaperId = exampaperIdList.get(randomIndex);
                }
                examSignMapper.saveExampaperIdByUserIdAndCourseId(userId, courseId,exampaperId);
                // 增加考试记录数据
                ExamLog examLog = new ExamLog();
                examLog.setExampaperId(exampaperId);
                examLog.setCourseId(courseId);
                examLog.setStuId(userId);
                examLog.setFlow(0);
                examLog.setExampaperGetScore(new BigDecimal(0));
                examLogService.save(examLog);

            }
        }

        // 根据试卷ID获取题目ID
        if (exampaperId != null) {
            List<Long> questionIdList = examquestionMapper.getQuestionIdByExampaperId(exampaperId);
            if (questionIdList != null && !questionIdList.isEmpty()) {
                // 根据题目ID获取题目信息
                questionList = questionMapper.stuFindQuestion(questionIdList,exampaperId);
            }
        }

        // 将题目返回
        Map<String, Object> questionMap = new HashMap<>();
        questionMap.put("records", questionList);
        questionMap.put("total", questionList.size());
        return questionMap;
    }

    @Override
    public Map<String, Object> findTrueResultPage(Long userId, Long exampaperId) {
        List<Question> questionList = new ArrayList<>();

        // 根据试卷ID获取题目ID
        if (exampaperId != null) {
            List<Long> questionIdList = examquestionMapper.getQuestionIdByExampaperId(exampaperId);
            if (questionIdList != null && !questionIdList.isEmpty()) {
                // 根据题目ID获取题目信息
                questionList = questionMapper.stufindTrueResultPage(questionIdList,exampaperId,userId);
            }
        }
        // 将题目返回
        Map<String, Object> questionMap = new HashMap<>();
        questionMap.put("records", questionList);
        questionMap.put("total", questionList.size());
        return questionMap;
    }

    @Override
    public Map<String, Object> stuFindTrueResultPage(Long userId, Long courseId) {
        List<Question> questionList = new ArrayList<>();

        // 根据学员ID和课程ID查询试卷ID
        Long exampaperId = examSignMapper.getExampaperIdByStuIdAndCourseId(userId, courseId);

        // 根据试卷ID获取题目ID
        if (exampaperId != null) {
            List<Long> questionIdList = examquestionMapper.getQuestionIdByExampaperId(exampaperId);
            if (questionIdList != null && !questionIdList.isEmpty()) {
                // 根据题目ID获取题目信息
                questionList = questionMapper.stufindTrueResultPage(questionIdList,exampaperId,userId);
            }
        }
        // 将题目返回
        Map<String, Object> questionMap = new HashMap<>();
        questionMap.put("records", questionList);
        questionMap.put("total", questionList.size());
        return questionMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePaper(Exampaper exampaper) {
        Integer count1 = exampaper.getCount();
        for (int i = 0; i < count1; i++) {
            Exampaper exampaper1 = new Exampaper();
            BeanUtil.copyProperties(exampaper, exampaper1, true);
            if (i != 0) {
                exampaper1.setName(exampaper1.getName() + "(" + i + ")");
            }
            exampaper1.setExampaperAllScore(new BigDecimal(100));
            exampaper1.setCreateTime(LocalDateTime.now());
            if(exampaper1.getId() == null) {
                saveOrUpdate(exampaper1);
                LambdaQueryWrapper<Question> questionQueryWrapper = new LambdaQueryWrapper<>();
                questionQueryWrapper.eq(Question::getIsDelete, 0);
                questionQueryWrapper.eq(Question::getCourseId, exampaper1.getCourseId());
                List<Question> questions = questionService.list(questionQueryWrapper);
                if (questions == null || questions.size() == 0) {
                    throw new RuntimeException("该课程题库下没有题目");
//                return Result.error("400","该课程题库下没有题目");
                }
                Map<String, List<Question>> map = questions.stream().collect(Collectors.groupingBy(Question::getQuestionType));
                Map<String, Integer> keyMap = new HashMap<>();
                if (exampaper1.getExampaperNum() == 20) {
                    keyMap.put("1", 10);
                    keyMap.put("2", 4);
                    keyMap.put("3", 4);
                    keyMap.put("4", 2);
                } else if (exampaper1.getExampaperNum() == 25) {
                    keyMap.put("1", 10);
                    keyMap.put("2", 5);
                    keyMap.put("3", 5);
                    keyMap.put("4", 5);
                } else {
                    keyMap.put("1", 20);
                    keyMap.put("2", 10);
                    keyMap.put("3", 10);
                    keyMap.put("4", 10);
                }
                List<Question> selectedQuestions = new ArrayList<>();
                Random random = new Random();
                for (Map.Entry<String, List<Question>> entry : map.entrySet()) {
                    String key = entry.getKey();
                    List<Question> questionList = new ArrayList<>(entry.getValue()); // 创建副本以避免修改原始数据
                    int numToSelect = keyMap.getOrDefault(key, 0);
                    if (questionList.isEmpty() || numToSelect <= 0) {
                        continue;
                    }
                    // 随机打乱题目顺序
                    Collections.shuffle(questionList, random);
                    if (numToSelect > questionList.size()) {
                        if (key.equals("1")) {
                            throw new RuntimeException("该课程题库下单选题数量不足");
//                        return Result.error("400","该课程题库下单选题数量不足");
                        } else if (key.equals("2")) {
//                        return Result.error("400","该课程题库下多选题数量不足");
                            throw new RuntimeException("该课程题库下多选题数量不足");
                        } else if (key.equals("3")) {
//                        return Result.error("400","该课程题库下判断题数量不足");
                            throw new RuntimeException("该课程题库下判断题数量不足");
                        } else {
//                        return Result.error("400","该课程题库下填空题数量不足");
                            throw new RuntimeException("该课程题库下填空题数量不足");
                        }
                    } else {
                        selectedQuestions.addAll(questionList.subList(0, numToSelect));
                    }
                }
                ArrayList<Examquestion> examquestions = new ArrayList<>();
                for (Question question:selectedQuestions) {
                    Examquestion examquestion = new Examquestion();
                    examquestion.setExampaperId(exampaper1.getId());
                    examquestion.setQuestionId(question.getId());
                    examquestion.setScore(new BigDecimal(100/exampaper1.getExampaperNum()));
                    examquestions.add(examquestion);
                }
                examquestionService.saveOrUpdateBatch(examquestions);
            } else {
                saveOrUpdate(exampaper1);
            }
        }
    }
}
